package com.earogya.logic.pharmacy.drugs_given_to_patient;

import java.util.Calendar;

import org.apache.struts.pharmacy.pharmacy.model.DrugsGivenToPatient;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.message.RDS_O13;

public class CreateRDSO13 {

	private RDS_O13 adt;
	private DrugsGivenToPatient dispence;
	
	public CreateRDSO13(DrugsGivenToPatient dispence){
		this.adt=new RDS_O13();
		this.dispence=dispence;
	}

	public String createMessage(String sendingFacility) throws HL7Exception{
		this.addMessageHeader(sendingFacility);
		this.addPatientDetails();
		this.addDrugDetails();
		return adt.getMessage().encode();
	}
	
	private void addMessageHeader(String sendingFacility) throws DataTypeException{
		adt.getMSH().getFieldSeparator().setValue("|");
		adt.getMSH().getEncodingCharacters().setValue("^~\\&");
		adt.getMSH().getDateTimeOfMessage().getTime().setValue(Calendar.getInstance().getTime());
		adt.getMSH().getMessageType().getMsg1_MessageCode().setValue("RDS");
		adt.getMSH().getMessageType().getTriggerEvent().setValue("O13");
		adt.getMSH().getSendingApplication().getUniversalID().setValue("CSTH");
		adt.getMSH().getVersionID().getVersionID().setValue("2.5.1");
		adt.getMSH().getSendingFacility().getUniversalID().setValue(sendingFacility);
		adt.getMSH().getReceivingApplication().getUniversalID().setValue("PAS");
		adt.getMSH().getReceivingFacility().getUniversalID().setValue(sendingFacility);
	}

	private void addDrugDetails() throws DataTypeException {
		adt.getORDER().getRXD().getDispenseGiveCode().getCe1_Identifier().setValue(dispence.getDrugId());
		adt.getORDER().getRXD().getRxd1_DispenseSubIDCounter().setValue(dispence.getNoOfIssues());
		adt.getORDER().getRXD().getRxd3_DateTimeDispensed().getTime().setValue(dispence.getDispenceDate());
		adt.getORDER().getRXD().getRxd4_ActualDispenseAmount().setValue(dispence.getDispencedQuantity());
		adt.getORDER().getRXD().getRxd5_ActualDispenseUnits().getCe1_Identifier().setValue(dispence.getDispenceAmountUnits());
		adt.getORDER().getRXD().getRxd6_ActualDosageForm().getCe1_Identifier().setValue(dispence.getDosage());
		adt.getORDER().getRXD().getRxd7_PrescriptionNumber().setValue(dispence.getPrescriptionNo());
		adt.getORDER().getRXD().getRxd10_DispensingProvider(0).getIDNumber().setValue(dispence.getDispencedByID());
		adt.getORDER().getORC().getOrc2_PlacerOrderNumber().getEi1_EntityIdentifier().setValue(dispence.getDispenceId());
	}
	
	private void addPatientDetails() throws DataTypeException {
		adt.getPATIENT().getPID().getPatientID().getCx1_IDNumber().setValue(dispence.getPatientId());	
	}
}
